<template>
  <view class="v-container-wrap bg-theme">
    <view class="transfer-form">
      <u-form :model="form">
        <u-row gutter="0" justify="between" align="top">
          <u-col span="6">
            <view class="layout" style="margin-right: 10rpx" :class="darkStyle">
              <view class="buy-wrapper" :class="['buy-wrapper-' + theme]">
                <view class="form-item-wrap">
                  <u-input
                    type="digit"
                    :border="false"
                    @input="handleBuyInput"
                    :cursor-spacing="0"
                    v-model="form.buyCount"
                    :placeholder="$t('tradeDetail.placeholder[1]')"
                    :customStyle="formLabelStyle"
                  ></u-input>
                  <view class="label">
                    {{ baseCurrency }}
                  </view>
                </view>
                <view class="percent-wrap">
                  <view
                    class="percent-item"
                    v-for="(item, index) in percent"
                    :key="index"
                    data-type="buy"
                    :data-value="item.val"
                    @click="onPercentClick"
                    >{{ item.text }}</view
                  >
                </view>
              </view>
              <view class="available">
                <view class="label">
                  {{ $t("tradeDetail.default[0]") }}
                </view>
                <view class="value">
                  <span>{{ $utils.fixed(mainAccount, 4) || "0.00" }}</span>
                  <span style="margin-left: 10rpx">{{
                    this.systemCurrency
                  }}</span>
                </view>
              </view>
              <view class="transfer-price">
                <view class="label">
                  {{ $t("tradeDetail.default[1]") }}
                </view>
                <view class="value">
                  {{ buyVolume ? `${buyVolume} ${systemCurrency}` : "--" }}
                </view>
              </view>
              <view class="button">
                <ex-button
                  type="buy"
                  :disabled="loading"
                  shape="circle"
                  @click="submitBuy"
                  >{{ $t("tradeDetail.button[0]") }}
                  {{ baseCurrency }}</ex-button
                >
              </view>
            </view>
          </u-col>
          <u-col span="6">
            <view class="layout" style="margin-left: 10rpx" :class="darkStyle">
              <view class="buy-wrapper" :class="['buy-wrapper-' + theme]">
                <view class="form-item-wrap">
                  <u-input
                    type="digit"
                    :border="false"
                    @input="handleSellInput"
                    v-model="form.sellCount"
                    :placeholder="$t('tradeDetail.placeholder[2]')"
                    :customStyle="formLabelStyle"
                  ></u-input>
                  <view class="label">
                    {{ baseCurrency }}
                  </view>
                </view>
                <view class="percent-wrap">
                  <view
                    class="percent-item"
                    v-for="(item, index) in percent"
                    :key="index"
                    data-type="sell"
                    :data-value="item.val"
                    @click="onPercentClick"
                    >{{ item.text }}</view
                  >
                </view>
              </view>
              <view class="available">
                <view class="label">
                  {{ $t("tradeDetail.default[0]") }}
                </view>
                <view class="value">
                  <span>{{ $utils.fixed(subAccount, 4) || "0.00" }}</span>
                  <span style="margin-left: 10rpx">{{ baseCurrency }}</span>
                </view>
              </view>
              <view class="transfer-price">
                <view class="label">
                  {{ $t("tradeDetail.default[1]") }}
                </view>
                <view class="value">
                  {{ sellVolume ? `${sellVolume} ${systemCurrency}` : "--" }}
                </view>
              </view>
              <view class="button">
                <ex-button
                  type="sell"
                  :disabled="loading"
                  shape="circle"
                  @click="submitSell"
                  >{{ $t("tradeDetail.button[1]") }}
                  {{ baseCurrency }}</ex-button
                >
              </view>
            </view>
          </u-col>
        </u-row>
      </u-form>
    </view>
    <view class="history">
      <view
        class="entrust-tabs-wrap"
        style="
          border-bottom: 2rpx solid var(--border-color);
          padding-bottom: 10rpx;
          padding-left: 30rpx;
          padding-right: 30rpx;
        "
      >
        <ex-tabs
          :list="tabs"
          :active="activeTab"
          :borderBottom="true"
          :fontWeight="false"
          @click="onTabClick"
          activeColor="brand"
        ></ex-tabs>
      </view>
      <order-history
        v-if="activeTab == 0"
        :matchId="match_id"
        ref="orderHistory"
      ></order-history>
    </view>
    <u-action-sheet
      :list="actionSheetList"
      v-model="entrustSheetShow"
      @click="entrustSheetCallback"
    ></u-action-sheet>
  </view>
</template>

<script>
import ExTabs from "@/components/ExTabs/ExTabs";
import OrderHistory from "@/components/trade/buy/OrderHistory";
import OpenOrder from "@/components/trade/buy/OpenOrder";
export default {
  components: {
    ExTabs,
    OrderHistory,
    OpenOrder,
  },
  props: {
    symbol: {
      type: String,
      default: "BTC/USDT",
    },
    match_id: {
      type: String | Number,
      default: null,
    },
    rSymbol: {
      type: String,
      default: "",
    },
    price: {
      type: Number | String,
      default: 0,
    },
  },
  data() {
    return {
      loading: false,
      entrustSheetShow: false,
      borderBottom: false,
      labelPosition: "top",
      border: true,
      inputHeight: 70,
      activeTab: 0,
      tabs: [
        {
          name: this.$t("tradeDetail.default[3]"),
        },
      ],
      percent: [
        {
          text: "25%",
          val: 0.25,
        },
        {
          text: "50%",
          val: 0.5,
        },
        {
          text: "75%",
          val: 0.75,
        },
        {
          text: "100%",
          val: 1,
        },
      ],
      form: {
        entrust: null,
        buyPrice: null,
        sellPrice: null,
        buyCount: null,
        sellCount: null,
      },
      mainAccount: 0, // usdt account
      subAccount: 0, // currency account
      actionIndex: 1,
      actionSheetList: [
        {
          text: this.$t("tradeDetail.default[4]"),
        },
        {
          text: this.$t("tradeDetail.default[5]"),
        },
      ],
      sub: {
        type: "sub",
        params: "",
      },
      market: "MARKET_DEPTH", // depth type
      buyVolume: 0,
      sellVolume: 0,
    };
  },
  computed: {
    currencyId() {
      // USDT ID
      if (this.currencyList.length > 0) {
        let item = this.currencyList.find((m) => {
          return m.code == this.systemCurrency;
        });
        if (item.id) return item.id;
        return 0;
      }
    },
    baseCurrency() {
      // return this.marketInfo.code;
      return this.symbol.split("/")[0]; // 去第一个数据, 不会报错
    },
  },
  mounted() {
    this.sub.params = `${this.market}.${this.rSymbol || this.symbol}`;
    this.form.entrust = this.actionSheetList[this.actionIndex].text;
    Promise.all([this.fetchCurrencyMatches(), this.fetchMarketDeal()]).then(
      (res) => {
        this.fetchAccount(this.currencyId);
        this.fetchAccount(this.marketInfo.id);
      }
    );
  },
  methods: {
    handleSellInput(value) {
      /**
       * @param {Object} value 处理
       */
      let sellVolume = Number(value) * Number(this.price);
      this.sellVolume = sellVolume.toFixed(4);
    },
    handleBuyInput(value) {
      /**
       * value: 当前币需要买入的数量
       */
      let buyVolume = Number(value) * Number(this.price);
      this.buyVolume =
        buyVolume <= Number(this.mainAccount)
          ? buyVolume.toFixed(4)
          : this.mainAccount;
    },
    refreshAccount() {
      this.fetchAccount(this.currencyId);
      this.fetchAccount(this.marketInfo.id);
    },
    handleReachBottom() {
      if (this.activeTab == 0) {
        this.$refs.orderHistory.fetchMore();
      }
    },
    onTabClick(active) {
      this.activeTab = Number(active);
    },
    websocket() {
      const _this = this;
      var socketTask = uni.connectSocket({
        url: this.$config.wss,
        complete: () => {},
      });
      this.socket = socketTask;
      socketTask.onOpen(() => {
        socketTask.send({
          data: JSON.stringify(_this.sub),
        });
      });
      socketTask.onMessage((res) => {
        const data = JSON.parse(res.data);
        _this.updateData(data);
      });
    },
    updateData(data) {
      if (data.type == this.market) {
        // 卖出的价格是买盘的最低价
        // 买入的价格是卖盘的最高价
        if (!data.depth) return;
        let inDepth = data.depth && data.depth.in;
        let outDepth = data.depth && data.depth.out;
        // 买盘的最低价
        let key = "price";
        this.form.sellPrice = this.$utils.getMin(inDepth, key);
        this.form.buyPrice = this.$utils.getMax(outDepth, key);
        this.socket.close();
      }
    },
    submitSell() {
      if (!this.form.sellCount || Number(this.form.sellCount) <= 0) {
        this.$u.toast(this.$t("tradeDetail.toast[2]"));
        return;
      }

      const path = "/spontaneous/add";
      const params = {
        currency_match_id: Number(this.match_id),
        number: Number(this.form.sellCount),
        direction: 2, // 买 1 卖 2
      };
      this.$emit("loading", true);
      this.$u
        .post(path, params)
        .then((res) => {
          this.$emit("loading", false);
          if (res.code == 1) {
            this.form.sellCount = null;
            this.sellVolume = null;
            this.$u.toast(res.msg);
            this.refreshAccount();
            if (this.$refs.orderHistory) {
              this.$refs.orderHistory.reload();
            }
          }
        })
        .catch((err) => {
          this.$emit("loading", false);
        });
    },
    submitBuy() {
      if (!this.form.buyCount || Number(this.form.buyCount) <= 0) {
        this.$u.toast(this.$t("tradeDetail.toast[0]"));
        return;
      }
      const path = "/spontaneous/add";
      const params = {
        currency_match_id: Number(this.match_id),
        number: Number(this.form.buyCount),
        direction: 1, // 买是1
      };
      this.$emit("loading", true);
      this.$u
        .post(path, params)
        .then((res) => {
          this.$emit("loading", false);
          if (res.code == 1) {
            this.form.buyCount = null;
            this.buyVolume = null;
            this.refreshAccount();
            if (this.$refs.orderHistory) {
              this.$refs.orderHistory.reload();
            }
            this.$u.toast(res.msg);
          }
        })
        .catch((err) => {
          this.$emit("loading", false);
        });
    },
    onPercentClick(e) {
      const type = e.currentTarget.dataset.type;
      const value = e.currentTarget.dataset.value;
      if (type === "buy") {
        if (Number(this.mainAccount) <= 0) return;
        let nums = Number(value) * Number(this.mainAccount);
        this.buyVolume = nums.toFixed(4);
        let buyCount = nums / Number(this.price);
        this.form.buyCount = buyCount.toFixed(4);
        return;
      }
      if (Number(this.subAccount) <= 0) return;
      let sellCount = Number(value) * Number(this.subAccount);
      this.form.sellCount = sellCount.toFixed(4);
      this.sellVolume = (sellCount * Number(this.price)).toFixed(4);
    },
    async fetchCurrencyMatches() {
      const path = "/market/currency_matches";
      const res = await this.$u.get(path);
      if (res.code == 1) {
        this.currencyList = res.data;
      }
    },
    async fetchMarketDeal() {
      const path = "/market/deal";
      const params = {
        currency_match_id: this.match_id,
      };
      const res = await this.$u.get(path, params);
      if (res.code == 1) {
        this.marketInfo = res.data.base_currency;
      }
    },
    async fetchAccount(id) {
      const path = "/account/detail";
      const params = {
        account_type_id: 1,
        currency_id: id,
      };
      const res = await this.$u.get(path, params);
      if (res.code == 1) {
        const data = res.data;
        if (data.currency.code == this.systemCurrency) {
          this.mainAccount = Number(data.balance);
          return;
        }
        this.subAccount = Number(data.balance);
      }
    },
    entrustSheetCallback(index) {
      this.actionIndex = Number(index);
      let item = this.actionSheetList[index];
      this.form.entrust = item.text;
    },
  },
};
</script>

<style lang="less" scoped>
.v-container-wrap {
  background-color: @white;
}

.transfer-form {
  padding: 0 30rpx;
  .input-item {
    font-size: 24rpx;
    font-weight: bold;
  }
}

.tips {
  color: @text-tips-color;
  font-size: 24rpx;
  display: flex;
  &.left {
    justify-content: flex-start;
  }
  &.right {
    justify-content: flex-end;
  }
}

.layout {
  &.darkStyle {
    .available {
      color: #8e8d92 !important;
    }
    .transfer-price {
      color: #8e8d92 !important;
      .percent-item {
      }
    }
  }
}

.buy-wrapper {
  border-radius: 8rpx;
  .form-item-wrap {
    display: flex;
    align-items: center;
    padding: 0 10rpx;
    .label {
      height: 100%;
      font-family: "DIN-Regular-2";
      font-size: 30rpx;
      padding: 0 20rpx;
      color: @text-content-color;
    }
  }
  .percent-wrap {
    display: flex;
    .percent-item {
      flex: 1;
      text-align: center;
      color: @text-tips-color;
      padding: 20rpx 0;
      font-size: 24rpx;
      &:last-child {
        border-right: none;
      }
    }
  }
}
.available {
  display: flex;
  justify-content: space-between;
  color: #090909;
  margin-top: 20rpx;
  font-size: 24rpx;
  .label {
  }
  .value {
  }
}
.transfer-price {
  margin-top: 30rpx;
  display: flex;
  color: #090909;
  justify-content: space-between;
  font-size: 24rpx;
  .value {
  }
}

.button {
  margin-top: 10rpx;
}

.empty-wrap {
  height: 500rpx;
  position: relative;
}

.entrust-content {
  .label {
    height: 40rpx;
    line-height: 40rpx;
    color: @text-tips-color;
    font-size: 26rpx;
    font-weight: bold;
    &.buy {
      color: @green;
    }
    &.sell {
      color: @red;
    }
  }
  .value {
    font-size: 24rpx;
    // color: @white;
    font-weight: bold;
    &.weight {
      font-weight: bold;
    }
  }
}

.entrust-card {
  border-bottom: 2rpx solid @border-color;
  padding: 30rpx 0;
}

.input-wrap {
  display: flex;
  height: 70rpx;
  border: 2rpx solid @border-color;
  border-radius: 8rpx;
  padding-left: 10rpx;
  overflow: hidden;
  .input-item {
  }
  .buttons {
    height: 100%;
    flex: 0 0 auto;
    display: flex;
    align-items: flex-start;
    flex-direction: column;
    font-size: 20rpx;
    color: #c8cbce;
    .up {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 50%;
      background-color: #f7f6fb;
      width: 60rpx;
    }
    .down {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 60rpx;
      background-color: #f7f6fb;
      height: 50%;
      flex: 1;
    }
  }
}
</style>
